package com.isoft.illustrationsdraw.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.isoft.illustrationsdraw.service.FileService;
import com.isoft.illustrationsdraw.service.IllustrationDTOService;
import com.isoft.illustrationsdraw.service.JWTService;
import com.isoft.illustrationsdraw.service.MediaService;
import com.isoft.illustrationsdraw.service.UserService;
import com.isoft.illustrationsdraw.dto.NewIllustrationDTO;
import com.isoft.illustrationsdraw.entity.User;
import com.isoft.illustrationsdraw.Constants;

@Service
public class MediaServiceImpl implements MediaService {


    private final FileService fileService;
    private final JWTService jwtService;
    private final IllustrationDTOService illustrationDTOService;
    private final UserService userService;

    public MediaServiceImpl(FileService fileService, JWTService jwtService, IllustrationDTOService illustrationDTOService, UserService userService) {
        this.fileService = fileService;
        this.jwtService = jwtService;
        this.illustrationDTOService = illustrationDTOService;
        this.userService = userService;
    }

    @Override
    public void uploadProfileImage(String token, MultipartFile file) throws IllegalArgumentException, IOException {
        Long userId = jwtService.getUserIdFromToken(token);
        if (userId == null) {
            throw new IllegalArgumentException(Constants.Error.INVALID_TOKEN);
        }
      
        try {
            File targetDir = fileService.createDirectory(Constants.File.PROFILEIMG_DIR + userId.toString());
            fileService.saveFiles(targetDir, List.of(file));
            User user = new User();
            user.setId(userId);
            var paths = fileService.listFilesInDirectory(targetDir);
            user.setProfileImg(paths.get(0));
            userService.updateById(user);
        } catch (Exception e) {
            throw e;
        }
    }

    @Transactional
    @Override
    public void handleUploadIllustrationRequest(String token, NewIllustrationDTO newIllustrationDTO, List<MultipartFile> files) throws IOException, IllegalArgumentException {
        Long userId = jwtService.getUserIdFromToken(token);
        if (userService.getById(userId).getIsBanned() == 1) {
            throw new IllegalArgumentException("banned user");
        }

        if (userId == null) {
            throw new IllegalArgumentException(Constants.Error.INVALID_TOKEN);
        }
        User user = userService.getById(userId);
        if (user.getIsBanned() == 1) {
            throw new IllegalArgumentException(Constants.Error.USER_BANNED);
        }

        List<File> savedFiles = new ArrayList<>();
        try {
            Long illustrationId = illustrationDTOService.addNewIllustrationBaseInfo(userId, newIllustrationDTO);

            // 创建目录
            File targetDir = fileService.createDirectory(Constants.File.ILLUSTRATIONS_DIR + illustrationId.toString() + "/");

            // 保存文件并记录成功的文件路径
            savedFiles = fileService.saveFiles(targetDir, files);

            // 获取文件路径
            List<String> paths = savedFiles.stream()
                                        .map(File::getAbsolutePath)
                                        .collect(Collectors.toList());

            // 保存文件集合
            illustrationDTOService.addNewIllustrationCollection(illustrationId, paths);
        } catch (Exception e) {
            // 清理已保存的文件
            for (File file : savedFiles) {
                if (file.exists()) {
                    file.delete();
                }
            }
            throw e;
        }
    }



    // @Override
    // public void handleUploadIllustrationRequest(String token, NewIllustrationDTO newIllustrationDTO, List<MultipartFile> files) throws IOException, IllegalArgumentException {
    //     Long userId = jwtService.getUserIdFromToken(token);
    //     if (userId == null) {
    //         throw new IllegalArgumentException(Constants.Error.INVALID_TOKEN);
    //     }
    //     try {
    //         Long illustrationId = illustrationDTOService.addNewIllustrationBaseInfo(userId, newIllustrationDTO);
    //         File targetDir = fileService.createDirectory(Constants.File.ILLUSTRATIONS_DIR + illustrationId.toString() + "/");
    //         fileService.saveFiles(targetDir, files);
    //         var paths = fileService.listFilesInDirectory(targetDir);
    //         illustrationDTOService.addNewIllustrationCollection(illustrationId, paths);
    //     } catch (Exception e) {
    //         throw e;
    //     }
    // }

}
